from typing import List

from sqlalchemy import select, delete, and_
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.functions.user import get_user
from app.database.models import User, Whitepage


async def add_whitepage(
    session: AsyncSession,
    telegram_id: int,
) -> None:

    user = await get_user(session, telegram_id)

    whitepage = Whitepage(user=user)

    session.add(whitepage)

    await session.commit()


async def get_user_whitepages(session: AsyncSession, user_id: int) -> List[Whitepage]:
    q = select(Whitepage).outerjoin(Whitepage.user).where(User.telegram_id == user_id)

    res = await session.execute(q)

    return res.scalars().all()


async def delete_user_whitepages(session: AsyncSession, user_id: int) -> None:

    user = await get_user(session, user_id, joined=True)

    q = delete(Whitepage).where(
        and_(Whitepage.user == user, Whitepage.status != "busy")
    )

    await session.execute(q)

    await session.commit()
